package com.base.log;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.base.exception.JailException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.validation.Valid;
import java.lang.annotation.Annotation;
import java.util.HashMap;

@Component
@Aspect
@Order(1)
@Slf4j
public class LogOutInterceptor {

    @Value("${system.jail}")
    private Integer jail;

    @Around("@annotation(com.base.log.LogOutAnnotation) && @annotation(logOutAnnotation)")
    public Object sneakLifeLogAround(ProceedingJoinPoint point, LogOutAnnotation logOutAnnotation) throws Throwable{
//        if (jail != 0 && RandomUtil.randomInt(1, 10) <= jail) {
//            throw new JailException(new HashMap<>());
//        }
        Object[] objects = point.getArgs();
        String url = logOutAnnotation.url();
        if (logOutAnnotation.request()) {
            Annotation[][] annotations = JoinPointUtil.getParameterAnnotations(point);
            Object validObject = JoinPointUtil.getParameterAnnotationObject(objects, annotations, Valid.class);
            if (validObject != null) {
                log.warn("请求接口" + url + "请求参数：【{}】", JSON.toJSONString(validObject));
            }
        } else {
            log.warn("请求接口" + url);
        }
        Object o = point.proceed(objects);
        log.warn("请求接口" + url + "返回数据：【{}】", JSON.toJSONString(o));
        return o;
    }

}
